#include <my_header.h>
#include <string.h>
#include <sys/file.h>

#define FILE_PATH "1.txt"
#define BUF_SIZE 4096

int main() {
    char chatbuf[BUF_SIZE] = {0};
    int fd;

    while (1) {
        // 1. B 等待A的消息（严格检查来源标记 "A:"）
        while (1) {
            fd = open(FILE_PATH, O_RDONLY);
            if (fd < 0) {
                perror("open failed");
                sleep(1);
                continue;
            }

            flock(fd, LOCK_EX);
            ssize_t msg_size = read(fd, chatbuf, sizeof(chatbuf) - 1);
            flock(fd, LOCK_UN);
            close(fd);

            if (msg_size > 0) {
                chatbuf[msg_size] = '\0';
                // 检查消息是否以 "A:" 开头
                if (strncmp(chatbuf, "A:", 2) == 0) {
                    printf("A say > %s", chatbuf + 2); // 去掉标记后输出
                    break;
                }
            }
            sleep(1);
        }

        // 2. B 获取用户输入并添加标记
        printf("B input > ");
        fflush(stdout);
        ssize_t read_count = read(STDIN_FILENO, chatbuf, sizeof(chatbuf) - 1);
        if (read_count <= 0) break;
        chatbuf[read_count] = '\0';

        // 添加来源标记 "B:"
        char marked_msg[BUF_SIZE];
        snprintf(marked_msg, sizeof(marked_msg), "B:%s", chatbuf);

        // 3. B 写入回复（加锁）
        fd = open(FILE_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0664);
        if (fd < 0) {
            perror("open failed");
            continue;
        }
        flock(fd, LOCK_EX);
        write(fd, marked_msg, strlen(marked_msg));
        flock(fd, LOCK_UN);
        close(fd);
    }
    return 0;
}
